var express = require('express');
var router = express.Router();
const {
    User
} = require('../models')
    //导入用于生成JWT字符串的包
const jwt = require('jsonwebtoken')


// 注册
router.post('/register', async function(req, res) {
    // 接收表单数据
    let username = req.body.username.trim()
    let password = req.body.password.trim()
    let repassword = req.body.repassword.trim()
    if (password !== repassword) {
        return res.cc(400, {
            code: 1001,
            msg: '密码和确认密码不一致'
        })
    }

    // 唯一性验证
    const users = await User.findAll({
        where: {
            username
        }
    })

    if (users && users.length > 0) {
        return res.cc(400, {
            code: 1002,
            msg: '用户名已经存在，请重新注册'
        })
    }
    await User.create({ username, password })
    return res.cc(200)
})


// 登录
router.post('/login', async function(req, res) {
    // 接收表单数据
    let username = req.body.username.trim()
    let password = req.body.password.trim()

    // 登录验证
    const users = await User.findAll({
        where: {
            username,
            password
        }
    })

    if (users && users.length > 0) {
        // 登录成功,返回用户登录成功的唯一性标识(token)
        let token = jwt.sign({
            user_id: users[0].id,
            username: users[0].username
        }, 'kuaijian', {
            expiresIn: 3600 * 10
        })

        return res.cc(200, {
            code: 200,
            msg: '登录成功',
            data: 'Bearer ' + token
        })
    } else {
        // 设置http状态码为400
        return res.cc(400, {
            code: 1004,
            msg: '用户名或者密码不正确，请重新登录'
        })
    }
})



module.exports = router;